package com.javafxboot.util;

import com.itextpdf.text.pdf.PdfReader;
import com.javafxboot.entity.HtmlEntity;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.printing.PDFPageable;
import org.apache.pdfbox.printing.PDFPrintable;
import org.apache.pdfbox.printing.Scaling;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageConfig;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfStamper;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.print.Book;
import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.PrinterJob;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class PdfPublic {

    public static void readPdf(HtmlEntity data) throws Exception{
        //try {

            File directory = new File("");//参数为空
            String courseFile = directory.getCanonicalPath() ;
            System.out.println(courseFile);

            Date dNow = new Date( );
            SimpleDateFormat ft = new SimpleDateFormat ("yyyy\\MM\\dd\\");
            ft.format(dNow);
            isexitsPath(""+ft.format(dNow)+"\\pdf");
            OutputStreamWriter pw = null;//定义一个流
            pw = new OutputStreamWriter(new FileOutputStream(ft.format(dNow)+""+data.getOrderSn()+"-j.html"),"UTF-8");//确认流的输出文件和编码格式，此过程创建了“test.txt”实例
            pw.write(data.getHtml());
            pw.close();//关闭流

            cmd(directory+"wkhtmltopdf\\bin\\wkhtmltopdf.exe -L 3 -R 0 -T 0 -B 0  --page-height 150 --page-width 100 --zoom 1.5 "+courseFile+"\\"+ft.format(dNow)+data.getOrderSn()+"-j.html "+courseFile+"\\"+ft.format(dNow)+data.getOrderSn()+"-j.pdf");

            addCode(courseFile+"\\"+ft.format(dNow)+data.getOrderSn()+"-j.pdf", data.getOrderSn());

            if(data.getIsPrint()){
                printFile(courseFile+"\\"+ft.format(dNow)+data.getOrderSn()+"-j.pdf");
            }

//        }catch (Exception e){
//            e.printStackTrace();
//        }

    }

    public static void addCode(String path, String orderSn) throws Exception {
        //模板的位置
        String typeB = path;
        InputStream inputStream = new FileInputStream(new File(typeB));
        PdfReader reader = new PdfReader(inputStream);
        OutputStream outputStream = new FileOutputStream(new File(path));
        PdfStamper stamper = new PdfStamper(reader, outputStream);
        //长和宽
        int qrcodeWidth = 144;
        //模板中空白处生成字符串的宽度最大180，如果超过这个宽度，字体就要相应的变小
        String qrcodeData = orderSn;
        PdfContentByte page = stamper.getOverContent(1);
        // 画中间的二维码
        Map<EncodeHintType, Object> config = new HashMap<EncodeHintType, Object>();

        MatrixToImageConfig con = new MatrixToImageConfig(Color.BLACK.getRGB(), Color.WHITE.getRGB());
        //此处二维码的长宽都是900像素，尽可能的让长宽大一些，然后调 image.scaleToFit(qrcodeWidth,qrcodeWidth);如果长宽太小的话 二维码会拉
        //伸后画上去，你会发现二维码背后有噪点，图像放大失真导致的，如果你画的二维码大一些，就不会存在放大失真的问题。
        BitMatrix bitMatrix = new MultiFormatWriter().encode(qrcodeData, BarcodeFormat.CODE_128, 900, 100, config);
        BufferedImage codeImage = MatrixToImageWriter.toBufferedImage(bitMatrix, con);
        ByteArrayOutputStream fos = new ByteArrayOutputStream();
        ImageIO.write(codeImage, "jpg", fos);
        Image image = Image.getInstance(fos.toByteArray());
        image.scaleToFit(qrcodeWidth, qrcodeWidth);
        //设置图片在页面中的坐标
        image.setAbsolutePosition(10, 390);
        page.addImage(image);
        stamper.close();
        reader.close();
        inputStream.close();
    }


    public static boolean isexitsPath(String path)throws InterruptedException{
        String [] paths=path.split("\\\\");
        StringBuffer fullPath=new StringBuffer();
        for (int i = 0; i < paths.length; i++) {
            fullPath.append(paths[i]).append("\\\\");
            File file=new File(fullPath.toString());
            if(paths.length-1!=i){//判断path到文件名时，无须继续创建文件夹！
                if(!file.exists()){
                    file.mkdir();
                    System.out.println("创建目录为："+fullPath.toString());
                }
            }
        }
        File file=new File(fullPath.toString());//目录全路径
        if (!file.exists()) {
            return true;
        }else{
            return false;
        }
    }

    /**
     * @param fileUrl		文件地址
     */
    public static void printFile(String fileUrl) throws Exception {
//        try {
            PdfReader pdfReader = new PdfReader(new FileInputStream(fileUrl));
            // 获取总页数
            int pages = pdfReader.getNumberOfPages();
            File file = new File(fileUrl);
            PDDocument document = PDDocument.load(file);
            PDFPrintable printable = new PDFPrintable(document);
            PrinterJob job = PrinterJob.getPrinterJob();
            job.setPrintable(printable);
            job.setPageable(new PDFPageable(document));
            Paper paper = new Paper();
            // 设置打印纸张大小
            paper.setSize(283,425); // 值为点 1 = 1/72 inch
            // 设置打印位置与坐标
            paper.setImageableArea(0, 0, paper.getWidth(), paper.getHeight()); // no margins
            PageFormat pageFormat = new PageFormat();
            pageFormat.setPaper(paper);
            Book book = new Book();
            PDFPrintable pdfPrintable = new PDFPrintable(document, Scaling.SCALE_TO_FIT);
            // 页码
            book.append(pdfPrintable, pageFormat, pages);
            job.setPageable(book);
            //设置打印份数
            job.setCopies(1);
            job.print();
//        }  catch (Exception e) {
//            e.printStackTrace();
//        }
    }


    public static boolean cmd(String command) throws Exception {
        boolean flag = false;
        String line = null;
        StringBuilder sb = new StringBuilder();
        Runtime runtime = Runtime.getRuntime();
//        try {
            Process process = runtime.exec(command);
            BufferedReader bufferedReader = new BufferedReader
                    (new InputStreamReader(process.getInputStream()));
            while ((line = bufferedReader.readLine()) != null) {

            }
            flag = true;
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        return flag;
    }

}
